package wsresource.server;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public class WSResource implements Connectable {
  private Properties properties;
  public WSResource(String propName) {
    properties = new Properties();
    try {
      InputStream in = this.getClass().
                       getResourceAsStream(propName + ".properties");
      properties.load(in);
    } catch (IOException ioe) {
    }
  }

  /**
   * Close the conection asocied with the context related a the transaction
   * identified whith xid
   * @param xid
   */
  @WebMethod
  public void close(String xid) {
    try {
      System.out.println("Close connection ");
      ResourceManager.getInstance().endConnection(xid, this);
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
    }
  }

  /**
   * Execute a SQL sentence including it within the transaction scope 
   * identified with xid.
   * @param stmt
   * @param xid
   * @throws Exception
   */
  @WebMethod()
  public void executeStatment(String stmt, String xid) throws Exception {
    System.out.println("WSResource: " + this);
    Connection conn = ResourceManager.getInstance().getConnection(xid, this);
    try {
      System.out.println("Execute statment '" + stmt + "'");
      conn.createStatement().executeUpdate(stmt);
    } catch (SQLException e) {
      ResourceManager.getInstance().markForRollback(xid);
      System.err.println(e.getMessage());
    }
  }

  public Properties getProperties() {
    return properties;
  }

  /**
   * Metodos de la interfaz Connectable
   */
  @WebMethod(exclude = true)
  public Connection beginConnection() {
    String driver = properties.getProperty("driver");
    String url = properties.getProperty("dburl");
    String login = properties.getProperty("login");
    String psw = properties.getProperty("psw");
    try {
      Class.forName(driver);
    } catch (ClassNotFoundException cnfe) {
      System.err.println(cnfe.getMessage());
    }
    //Establish Connection
    Connection conn;
    try {
      conn = DriverManager.getConnection(url, login, psw);
      return conn;
    } catch (SQLException e) {
      System.err.println(e.getMessage());
    }
    return null;
  }

  @WebMethod(exclude = true)
  public void endConnection(Connection conn) {
    try {
      conn.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}